package com.ybe.server;

import com.sun.net.httpserver.HttpServer;
import com.ybe.handler.http.RootPathRouterHandler;
import com.ybe.session.SessionHolder;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.*;

public class BetServer {

    private final int port;

    private HttpServer server;

    public BetServer(int port) {

        this.port = port;
    }

    public void start() {
        try {
            // 1. 创建服务器（端口 8080）
            server = HttpServer.create(new InetSocketAddress(port), 0);

            // 2 单一处理器处理所有带前缀的路径
            server.createContext("/", new RootPathRouterHandler());

            int cores = Math.max(1, Runtime.getRuntime().availableProcessors());
            ThreadPoolExecutor executor = new ThreadPoolExecutor(
                    cores, cores * 4,
                    60L, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(10000),
                    r -> {
                        Thread t = new Thread(r, "http-worker");
                        t.setDaemon(true);
                        return t;
                    },
                    new ThreadPoolExecutor.AbortPolicy()
            );
            server.setExecutor(executor);

            // Background session cleanup (very light)
            ScheduledExecutorService cleaner = Executors.newSingleThreadScheduledExecutor(r -> {
                Thread t = new Thread(r, "session-cleaner");
                t.setDaemon(true);
                return t;
            });
            cleaner.scheduleAtFixedRate(this::purgeExpiredSessions, 1, 1, TimeUnit.MINUTES);

            // 3. 启动服务器
            server.start();
            System.out.println("Server started on http://localhost:" + port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    public void stop() {
        server.stop(0);
        System.out.println("Server stoped ");
    }

    private void purgeExpiredSessions() {
        SessionHolder.removeExpiredSessions();
    }
}
